using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Xml;

namespace NAst.Common
{
    /// <summary>
    /// Copy file from one folder to another
    /// </summary>
    [Netlet("CopyFiles")]
    public class CopyFilesNetlet : INetlet
    {
        public string _sourceFolder;
        public string _destFolder;
        public string _searchPattern;

        public List<string> _copiedFiles = new List<string>();
        public bool _wasFolderCreationNeeded = false;

        #region INetlet Members
        public void Initialize(string stateName, System.Xml.XmlElement config)
        {
            _sourceFolder = config.GetAttribute("sourceFolder");
            _destFolder = config.GetAttribute("destinationFolder");
            _searchPattern = config.GetAttribute("searchPattern");
            if (string.IsNullOrEmpty(_searchPattern)) _searchPattern = "*.*";


            _destFolder = ExpandVariables(_destFolder);
            _sourceFolder = ExpandVariables(_sourceFolder);
        }

        private static string ExpandVariables(string name)
        {
            string retVal = Environment.ExpandEnvironmentVariables(name);

            retVal = retVal.Replace("%DESKTOP%", Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
            retVal = retVal.Replace("%PROGRAMSMENU%", Environment.GetFolderPath(Environment.SpecialFolder.Programs));
            retVal = retVal.Replace("%PICTURES%", Environment.GetFolderPath(Environment.SpecialFolder.MyPictures));
            retVal = retVal.Replace("%SENDTO%", Environment.GetFolderPath(Environment.SpecialFolder.SendTo));
            retVal = retVal.Replace("%TEMPLATES%", Environment.GetFolderPath(Environment.SpecialFolder.Templates));
            retVal = retVal.Replace("%STARTUP%", Environment.GetFolderPath(Environment.SpecialFolder.Startup));

            return retVal;
        }

        public void Connect()
        {
            _copiedFiles.Clear();

            try
            {
                if (!Directory.Exists(_destFolder))
                {
                    _wasFolderCreationNeeded = true;
                    Directory.CreateDirectory(_destFolder);
                }

                foreach (string file in Directory.GetFiles(_sourceFolder, _searchPattern))
                {
                    string destFile = Path.Combine(_destFolder,
                        Path.GetFileName(file));
                    File.Copy(file, destFile, true);
                    _copiedFiles.Add(destFile);
                }
            }
            catch(Exception e)
            {
                Trace.TraceError(string.Format("Unable to copy files from the requested folder {0} : {1}",
                    _sourceFolder, e.Message));
                System.Diagnostics.EventLog.WriteEntry("NetworkAsssitant", string.Format("Unable to copy files from the requested folder {0} : {1}",
                    _sourceFolder, e.Message), System.Diagnostics.EventLogEntryType.Warning);
                throw;
            }
        }

        public void Disconnect()
        {
            if (_wasFolderCreationNeeded)
                Directory.Delete(_destFolder, true);
            else
            {
                foreach (string file in _copiedFiles)
                {
                    try
                    {
                        File.Delete(file);
                    }
                    catch(Exception e)
                    {
                        Trace.TraceError(string.Format("Unable to remove file {0} : {1}",
                            file, e.Message));
                        System.Diagnostics.EventLog.WriteEntry("NetworkAsssitant", string.Format("Unable to remove file {0} : {1}",
                            file, e.Message), System.Diagnostics.EventLogEntryType.Warning);
                    }
                }
            }
        }

        public void SaveState(XmlElement elmToSaveTo)
        {
            elmToSaveTo.SetAttribute("sourceFolder", _sourceFolder);
            elmToSaveTo.SetAttribute("destinationFolder", _destFolder);
            elmToSaveTo.SetAttribute("searchPattern", _searchPattern);
            elmToSaveTo.SetAttribute("wasFolderCreated", _wasFolderCreationNeeded.ToString());

            foreach (string file in _copiedFiles)
            {
                XmlElement elm = elmToSaveTo.OwnerDocument.CreateElement("File");
                elm.SetAttribute("path", file);
                elmToSaveTo.AppendChild(elm);
            }
        }

        public void LoadState(System.Xml.XmlElement elmToLoadFrom)
        {
            _copiedFiles.Clear();

            _sourceFolder = elmToLoadFrom.GetAttribute("sourceFolder");
            _destFolder = elmToLoadFrom.GetAttribute("destinationFolder");
            _searchPattern = elmToLoadFrom.GetAttribute("searchPattern");
            _wasFolderCreationNeeded = false;
            bool.TryParse(elmToLoadFrom.GetAttribute("wasFolderCreated"), out _wasFolderCreationNeeded);

            foreach (XmlElement elm in elmToLoadFrom.SelectNodes("./File"))
            {
                string fil = elm.GetAttribute("path");
                if (File.Exists(fil))
                    _copiedFiles.Add(fil);
            }
        }

        #endregion
    }
}
